package com.macro.mall.start;

import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.alibaba.nacos.shaded.com.google.gson.reflect.TypeToken;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.demo.dto.IndexDto;
import com.macro.mall.rement.EsConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.FileReader;
import java.lang.reflect.Type;
import java.util.Map;

@Component
@Slf4j
public class EsStart implements ApplicationRunner {
    @Autowired
    private EsConfig esConfig;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        String path = "mall-admin/src/main/resources/esmappings/es.json";
        Gson gson = new Gson();
        Type type = new TypeToken<Map<String, Object>>() {}.getType();

        BufferedReader bufferedReader = new BufferedReader(new FileReader(path));
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line);
        }
        bufferedReader.close();

        String jsonString = stringBuilder.toString();
        Map<String,Object> map = gson.fromJson(jsonString, type);
        String json = gson.toJson(map.get("mappings"));

        // 判断 索引是否存在
        IndexDto indexDto = new IndexDto();

        CommonResult exists = esConfig.exists(map.get("indexName").toString());

        if (!exists.getData().equals(true)) {
            indexDto.setMappings(json);
            System.out.println("==================="+indexDto.getMappings());
            indexDto.setSettings(jsonString);
            esConfig.foundIndex(indexDto);
        }

    }



}
